<?php

ini_set('display_errors',"stderr");

session_start();

require_once("../classes/Factory.php");
require_once("../classes/project/TaskBuilder.php");
require_once("../classes/tracking/TimeEntry.php");
require_once("../classes/dates/DateEncoder.php");


// is user logged on ? --------------------------------------------
if (!isset($_SESSION['user'])) { header("location: ./logon.php"); }
// ----------------------------------------------------------------

$left="../templates/misc/menu.php";
$data="../templates/editTask.php";
$userInfo = "../templates/misc/userInfo.php";
$alert = "";

$u = new SimpleXMLElement($_SESSION['user']);
$project = Factory::buildFromFile("Project", $_SESSION['project']);
$timeSheet = Factory::buildFromFile("TimeSheet", $_SESSION['timesheet']);

	
if (isset($_GET['TaskUID'])) {
	$selectedTask = $_GET['TaskUID'];
} elseif (isset($_POST['TaskUID'])) {
	$selectedTask = $_POST['TaskUID'];
} else {
	$selectedTask = 0;	
}

if (isset($_GET['TrackID'])) {
	$selectedTrack = $_GET['TrackID'];
} elseif (isset($_POST['TrackID'])) {
	$selectedTrack = $_POST['TrackID'];
} else {
	$selectedTrack = -1;	
}

$task = Factory::buildTask($selectedTask, $project);
if ($selectedTrack != -1) {
	$timeEntry = $timeSheet->getById($selectedTrack);
} else {
	$timeEntry = Factory::newTimeEntry();
}

// update / save entry
if (isset($_POST) && $_POST['action'] == "update") {
	$date = DateEncoder::decodeForm($_POST['day'], $_POST['week']);
	$tte = Factory::newTimeEntry();
	$tte->setEntry( (string) $u['uid'],
					$selectedTask,
					$date,
				 	$_POST['duration'],
					$_POST['name'],
					$_POST['note']);
	
	if ($selectedTrack != -1) {
		$track = $tte;
	} else {
		$timeSheet->appendEntry($tte);		
	}		
	if ($timeSheet->save()) {
		$confirm = "Modifications enregistrées.";
	} else {
		$alert = "Les modifications n'ont pas été enregistrées !";
	}
} elseif (isset($_POST) && $_POST['action'] == "delete") {
	if ( isset($_POST['UID']) && $timeSheet->deleteEntry($_POST['UID'])) {
		$confirm = "Entrée supprimée";
	} else {
		$alert = "L'entrée n'a pas été supprimée";
	}
}

$Entries = $timeSheet->getByTaskUID($selectedTask);

include("../templates/main.php");

?>
